/*
 * @Author: MuQuanyu(MQy)
 * @Date: 2025-09-04 14:47:24
 * @LastEditTime: 2025-10-14 10:52:07
 * @email: muquanyu@outlook.com
 */

// 全局导航首位
import router from "@/router";
import { buildRoutesFromServer, extractKeepAliveList } from "@/utils/route/index";
import { GetSysRouteTree, GetUserInfo } from "@/api/sys/user";
import tool from "@/utils/common/index";
import { useSysStore, useAuthStore } from "@/store";

let isDynamicRoutesAdded = false; // 动态路由是否已添加完毕

router.beforeEach(async (to, from, next) => {
  const sysStore = useSysStore();
  const authStore = useAuthStore();
  sysStore.setIsProcess(true);
  if (from.path == "/login") {
    sysStore.setIsLoading(true);
  }

  // 判断是否登录，只需调个人信息接口即可
  if (to.path !== "/login") {
    try {
      sysStore.setIsPageLoading(true);
      let userInfoRes = await GetUserInfo();
      if (userInfoRes.code == 200) {
        authStore.setUserInfo(userInfoRes.data);
        authStore.setIsLogin(true);
      }
    } catch (error) {
      authStore.setUserInfo(null);
      authStore.setIsLogin(false);
    } finally {
      sysStore.setIsPageLoading(false);
    }
  }

  if (!authStore.isLogin && to.path !== "/login") {
    // 1. 未登录且非登录页 → 跳转登录
    sysStore.setProcessFinish(true);
    sysStore.setIsLoading(false);
    next("/login");
    return;
  }

  // 2. 已登录但访问登录页了 => 跳转到首页
  if (authStore.isLogin && to.path == "/login") {
    sysStore.setProcessFinish(true);
    sysStore.setIsLoading(false);
    next("/");
    return;
  }

  // 3. 已登录但未加载动态路由 → 去加载路由
  if (authStore.isLogin && !isDynamicRoutesAdded) {
    try {
      const res = await GetSysRouteTree();

      if (res.code === 200) {
        const asyncRoutes = buildRoutesFromServer(res.data as any);
        authStore.setDynamicRoutes(asyncRoutes);
        // console.log("dynamicRoutes => ", authStore.dynamicRoutes);
        const keepAliveList = extractKeepAliveList(asyncRoutes);

        authStore.setKeepAliveList(keepAliveList);
        // console.log("keepAliveList => ", authStore.keepAliveList);
        asyncRoutes.forEach((route) => {
          router.addRoute(route); // 动态添加路由
        });

        // 3. 确保 404 路由最后添加（避免抢占）
        router.addRoute({
          path: "/:pathMatch(.*)*",
          name: "NotFound",
          component: () => import("@/views/Other/404.vue"),
        });

        router.addRoute({
          path: "/",
          redirect: router.getRoutes()[0].path,
        });

        if (authStore.topLabelList.length == 0) {
          const firstTopLabel: TopLabel = {
            path: router.getRoutes()[0].meta?.fullPath as string,
            title: router.getRoutes()[0].meta?.title as string,
            iconType: router.getRoutes()[0].meta?.iconType as string,
            icon: router.getRoutes()[0].meta?.icon as string,
          };
          authStore.setTopLabelList([firstTopLabel]);
        }

        isDynamicRoutesAdded = true;
        // console.log("路由加载完成 => ", router.getRoutes());

        // 4. 重定向到目标页（确保新路由生效）

        sysStore.setProcessFinish(true);
        sysStore.setIsLoading(false);
        next(to.fullPath);
        return;
      }
    } catch (error) {
      console.error("路由加载失败:", error);
      sysStore.setProcessFinish(true);
      sysStore.setIsLoading(false);
      next("/login"); // 失败时退回登录页
      return;
    }
  }

  // 5. 正常放行
  sysStore.setProcessFinish(true);
  sysStore.setIsLoading(false);
  next();
});

router.afterEach((to, from) => {
  const authStore = useAuthStore();
  const sysStore = useSysStore();

  let existIndex = authStore.topLabelList.findIndex(
    (x) => x.path == router.currentRoute.value.fullPath
  );
  if (existIndex < 0) {
    const currentLabelIndex = router
      .getRoutes()
      .findIndex((x) => x.meta.fullPath == router.currentRoute.value.fullPath);

    console.log("当前url =>", router.currentRoute.value.fullPath);
    if (currentLabelIndex >= 0) {
      const currentLabel = router.getRoutes()[currentLabelIndex];
      const tempTopLabelList = authStore.topLabelList;
      tempTopLabelList.push({
        path: currentLabel.meta?.fullPath as string,
        title: currentLabel.meta?.title as string,
        iconType: currentLabel.meta?.iconType as string,
        icon: currentLabel.meta?.icon as string,
      });
      authStore.setTopLabelList(tempTopLabelList);
    }
  }

  // 下方是判断当前主题模式与主题色的
  switch (sysStore.themeMode) {
    case "light": {
      document.documentElement.classList.remove("dark");
      break;
    }
    case "dark": {
      document.documentElement.classList.add("dark");
      break;
    }
    default: {
      // 获取当前时间
      const now = new Date();
      // 获取当前小时（24小时制）
      const currentHour = now.getHours();

      // 判断是否为白天（6:00 - 18:00）
      const isDaytime = currentHour >= 6 && currentHour < 18;
      if (!isDaytime) {
        document.documentElement.classList.add("dark");
      } else {
        document.documentElement.classList.remove("dark");
      }
    }
  }
  if (tool.getLocalStore("yu-isShowLogo") == null) {
    sysStore.setIsShowLogo(true);
  }
  if (tool.getLocalStore("yu-isPersistenceTopLabelBar") == null) {
    sysStore.setIsPersistenceTopLabelBar(true);
  }
});
